package com.banciyuan.bcywebview.biz.search;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.base.factory.TimelineFactory;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase.OnLastItemVisibleListener;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshListView;
import com.banciyuan.bcywebview.biz.main.group.hot.GroupHotAdapterSearch;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.daoexample.model.SearchContent;
import de.greenrobot.daoexample.model.TagDetail;
import de.greenrobot.daoexample.model.Team;

public class SearchGroupFragment extends SearchBaseFragment {

    public static final int TAG = 0;
    private PullToRefreshListView mRefreshLv;
    private ListView mContentLv;
    private GroupHotAdapterSearch groupHotAdapter;
    private SearchComplexAdapter searchContentAdapter;
    private String filter_name = "group";
    private List<Team> mShowList = new ArrayList<Team>();
    private List<SearchContent> mSearchList = new ArrayList<SearchContent>();

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.search_complex_fragment, container, false);
        initArgs();
        initUi(rootView);
        initAction();
        initProgressbar(rootView);
        return rootView;
    }

    @Override
    protected void initArgs() {
        query = getArguments().getString("query");
    }

    @Override
    public void fetchData() {
        initData();
    }

    @Override
    protected void initUi(View rootView) {
        mRefreshLv = (PullToRefreshListView) rootView.findViewById(R.id.search_refresh_lv);
        mContentLv = mRefreshLv.getRefreshableView();
    }

    @Override
    protected void initAction() {
        mRefreshLv.setOnRefreshListener(new OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                end_flag = false;
                loading = false;
                page = 1;
                initData();
            }
        });

        mRefreshLv.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if (!loading && !end_flag) {
                    page++;
                    initData();
                }
            }
        });
    }

    @Override
    protected void initData() {
        loading = true;
        if (StringUtil.notNullEqual(filter_name, "group")) {
            getGroup();
        } else {
            getAnswer();
        }
    }

    private void getGroup() {
        SearchHelper searchHelper = new SearchHelper(getActivity(), new ISearchhelper() {
            @Override
            public void succ(String type, String succ) {
                dealGroup(succ);
            }

            @Override
            public void fail(String type) {
                mProgressbarHelper.onFailed();
                loading = false;
            }
        });
        searchHelper.getSearch("group", page, query);
    }

    private void getAnswer() {
        SearchHelper searchHelper = new SearchHelper(getActivity(), new ISearchhelper() {
            @Override
            public void succ(String type, String succ) {
                dealAnswer(succ);
            }

            @Override
            public void fail(String type) {
                mProgressbarHelper.onFailed();
                loading = false;
            }
        });
        searchHelper.getSearch("post", page, query);
    }


    private void dealAnswer(String result) {
        try {
            Gson gson = new Gson();
            List<SearchContent> templist = new ArrayList<SearchContent>();
            JSONObject response = new JSONObject(result);
            JSONObject data = response.getJSONObject(HttpUtils.UPLOAD_DATA);
            JSONArray results = data.getJSONArray("results");
            if (page == 1) {
                String count = data.getString("total");
                SearchContent searchContent = new SearchContent();
                searchContent.setTitle_num_format(String.format(getString(R.string.releated_answer_pink), count));
                templist.add(searchContent);
            }
            List<SearchContent> templist2 = gson.fromJson(results.toString(), new TypeToken<List<SearchContent>>() {
            }.getType());
            if (templist2.size() == 0) {
                end_flag = true;
            }
            templist.addAll(SearchHelper.popIllegal(templist2, TimelineFactory.TIMELINE_TYPE_GROUP));
            setWorkToTagForSearchContent(templist);
            setContentAdapter(templist);
            loading = false;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void dealGroup(String result) {
        try {
            Gson gson = new Gson();
            List<Team> templist = new ArrayList<Team>();
            JSONObject response = new JSONObject(result);
            JSONObject data = response.getJSONObject(HttpUtils.UPLOAD_DATA);
            JSONArray results = data.getJSONArray("results");
            if (page == 1) {
                String count = data.getString("total");
                Team team1 = new Team(String.format(getString(R.string.releated_topic_pink), count));
                team1.setType("title");
                templist.add(team1);
            }
            List<Team> templist2 = gson.fromJson(results.toString(), new TypeToken<List<Team>>() {
            }.getType());

            if (templist2.size() == 0) {
                end_flag = true;
            }
            templist.addAll(SearchHelper.popIllegal(templist2));
            setWorkToTagForTeam(templist);
            setAdapter(templist);
            loading = false;
        } catch (Exception e) {
            e.printStackTrace();
            loading = false;
        }
    }

    private void setWorkToTagForTeam(List<Team> templist) {
        for (Team h : templist) {
            if (!TextUtils.isEmpty(h.getWork())) {
                TagDetail tagDetail = new TagDetail();
                tagDetail.setWork(h.getWork());
                tagDetail.setWid(h.getId());
                tagDetail.setTag_name(h.getWork());
                h.getTags().add(0, tagDetail);
            }
        }
    }

    private void setWorkToTagForSearchContent(List<SearchContent> templist) {
        for (SearchContent h : templist) {
            if (!TextUtils.isEmpty(h.getWork())) {
                TagDetail tagDetail = new TagDetail();
                tagDetail.setWork(h.getWork());
                tagDetail.setWid(h.getWid());
                tagDetail.setTag_name(h.getWork());
                h.getTags().add(0, tagDetail);
            }
        }
    }

    private void setContentAdapter(List<SearchContent> templist) {
        if (page == 1) {
            mSearchList.clear();
        }
        mSearchList.addAll(templist);
        if (page == 1) {
            searchContentAdapter = new SearchComplexAdapter(mSearchList, getActivity());
            mContentLv.setAdapter(searchContentAdapter);
        } else {
            searchContentAdapter.notifyDataSetChanged();
        }
        mRefreshLv.onRefreshComplete();
        mProgressbarHelper.onSuccess();
    }


    private void setAdapter(List<Team> templist) {
        if (page == 1) {
            mShowList.clear();
        }
        mShowList.addAll(templist);
        if (page == 1) {
            groupHotAdapter = new GroupHotAdapterSearch(getActivity(), mShowList);
            mContentLv.setAdapter(groupHotAdapter);
        } else {
            groupHotAdapter.notifyDataSetChanged();
        }
        mRefreshLv.onRefreshComplete();
        mProgressbarHelper.onSuccess();
    }

}